package org.jdns.jfreechess.ics;

import java.io.IOException;
import java.io.InputStream;

public class IcsMessageReader {
  private final InputStream stream;
  private StringBuilder buffer = new StringBuilder();

  private final byte[] prompt;

  public IcsMessageReader(InputStream stream, String prompt) {
    this.stream = stream;
    this.prompt = prompt.getBytes();
  }

  public String readMessage() throws IOException {
    while (true) {
      int read = stream.read();
      if (read == -1) {
        if (buffer.length() > 0) {
          return clearAndReturnBuffer();
        } else {
          return null;
        }
      }

      if (buffer.length() == 0 && read == '\n') {
        continue;
      }

      buffer.append((char) read);
      if (bufferEndsWithPrompt()) {
        buffer.delete(buffer.length() - prompt.length, buffer.length());

        if (buffer.length() > 0) {
          return clearAndReturnBuffer();
        }
      }
    }
  }

  private String clearAndReturnBuffer() {
    String result = buffer.toString();
    buffer = new StringBuilder();
    return result;
  }

  private boolean bufferEndsWithPrompt() {
    if (buffer.length() >= prompt.length) {
      // have we got the prompt at the end of this thing?
      for (int i = 0; i < prompt.length; i++) {
        int bufferIndex = i + (buffer.length() - prompt.length);
        if (buffer.charAt(bufferIndex) != prompt[i]) {
          return false;
        }
      }

      return buffer.length() == prompt.length
          || buffer.charAt(buffer.length() - prompt.length - 1) == '\n';
    }

    return false;
  }


}
